package com.example.usb.dao;

import android.database.Cursor;
import android.database.SQLException;
import android.text.TextUtils;

import com.example.usb.greendao.DaoMaster;
import com.lib.uvccamera.utils.DebugLog;

import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.internal.DaoConfig;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * created by liangkun on 2019/2/13
 * Describe:数据库升级辅助类
 */

public class MigrationHelper {
    private static MigrationHelper instance;
    private static String TAG = "MigrationHelper ";
    private static final String SQLITE_MASTER = "sqlite_master"; //正式
    private static final String SQLITE_TEMP_MASTER = "sqlite_temp_master"; //临时

    public static MigrationHelper getInstance() {
        if (instance == null) {
            instance = new MigrationHelper();
        }
        return instance;
    }

    /**
     * 迁移数据表
     *
     * @param db         数据库
     * @param daoClasses 类
     */
    public void migrate(Database db, Class<? extends AbstractDao<?, ?>>... daoClasses) {
        DebugLog.d(TAG + "【Generate temp table】start");
        generateTempTables(db, daoClasses);
        DebugLog.d(TAG + "【Generate temp table】complete");

        DaoMaster.dropAllTables(db, true);
        DaoMaster.createAllTables(db, false);
        DebugLog.d(TAG + "【restoreData temp table】start");
        restoreData(db, daoClasses);
        DebugLog.d(TAG + "【restoreData temp table】complete");
    }

    /**
     * 生成临时列表
     *
     * @param db         数据库
     * @param daoClasses 类
     */
    private void generateTempTables(Database db, Class<? extends AbstractDao<?, ?>>... daoClasses) {
        for (int i = 0; i < daoClasses.length; i++) {
            String tempTableName = null;

            DaoConfig daoConfig = new DaoConfig(db, daoClasses[i]);
            String tableName = daoConfig.tablename;
            if (!isTableExists(db, false, tableName)) {
                DebugLog.d(TAG + "【New Table】" + tableName);
                continue;
            }
            try {
                tempTableName = daoConfig.tablename.concat("_TEMP");
                StringBuilder dropTableStringBuilder = new StringBuilder();
                dropTableStringBuilder.append("DROP TABLE IF EXISTS ").append(tempTableName).append(";");
                db.execSQL(dropTableStringBuilder.toString());

                StringBuilder insertTableStringBuilder = new StringBuilder();
                insertTableStringBuilder.append("CREATE TEMPORARY TABLE ").append(tempTableName);
                insertTableStringBuilder.append(" AS SELECT * FROM ").append(tableName).append(";");
                db.execSQL(insertTableStringBuilder.toString());
                DebugLog.d(TAG + "【Table】" + tableName + "\n ---Columns-->" + getColumnsStr(daoConfig));
                DebugLog.d(TAG + "【Generate temp table】" + tempTableName);
            } catch (SQLException e) {
                DebugLog.d(TAG + "【Failed to generate temp table】" + tempTableName + e.toString());
            }
        }
    }

    /**
     * 表是否存在
     * @param db 数据库
     * @param isTemp 是否存在
     * @param tableName 表名
     * @return 判断
     */
    private static boolean isTableExists(Database db, boolean isTemp, String tableName) {
        if (db == null || TextUtils.isEmpty(tableName)) {
            return false;
        }
        String dbName = isTemp ? SQLITE_TEMP_MASTER : SQLITE_MASTER;
        String sql = "SELECT COUNT(*) FROM " + dbName + " WHERE type = ? AND name = ?";
        Cursor cursor = null;
        int count = 0;
        try {
            cursor = db.rawQuery(sql, new String[]{"table", tableName});
            if (cursor == null || !cursor.moveToFirst()) {
                return false;
            }
            count = cursor.getInt(0);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return count > 0;
    }

    /**
     * 获得表名
     * @param daoConfig 属性
     * @return 表名
     */
    private static String getColumnsStr(DaoConfig daoConfig) {
        if (daoConfig == null) {
            return "no columns";
        }
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < daoConfig.allColumns.length; i++) {
            builder.append(daoConfig.allColumns[i]);
            builder.append(",");
        }
        if (builder.length() > 0) {
            builder.deleteCharAt(builder.length() - 1);
        }
        return builder.toString();
    }

    /**
     * 储存数据
     * @param db 数据库
     * @param daoClasses 数据库类
     */
    private static void restoreData(Database db, Class<? extends AbstractDao<?, ?>>... daoClasses) {
        for (int i = 0; i < daoClasses.length; i++) {
            DaoConfig daoConfig = new DaoConfig(db, daoClasses[i]);
            String tableName = daoConfig.tablename;
            String tempTableName = daoConfig.tablename.concat("_TEMP");

            if (!isTableExists(db, true, tempTableName)) {
                continue;
            }

            try {
                // get all columns from tempTable, take careful to use the columns list
                List<String> columns = getColumns(db, tempTableName);
                ArrayList<String> properties = new ArrayList<>(columns.size());
                for (int j = 0; j < daoConfig.properties.length; j++) {
                    String columnName = daoConfig.properties[j].columnName;
                    if (columns.contains(columnName)) {
                        properties.add(columnName);
                    }
                }
                if (properties.size() > 0) {
                    final String columnSQL = TextUtils.join(",", properties);

                    StringBuilder insertTableStringBuilder = new StringBuilder();
                    insertTableStringBuilder.append("INSERT INTO ").append(tableName).append(" (");
                    insertTableStringBuilder.append(columnSQL);
                    insertTableStringBuilder.append(") SELECT ");
                    insertTableStringBuilder.append(columnSQL);
                    insertTableStringBuilder.append(" FROM ").append(tempTableName).append(";");
                    db.execSQL(insertTableStringBuilder.toString());
                    DebugLog.d(TAG + "【Restore data】 to " + tableName);
                }
                StringBuilder dropTableStringBuilder = new StringBuilder();
                dropTableStringBuilder.append("DROP TABLE ").append(tempTableName);
                db.execSQL(dropTableStringBuilder.toString());
                DebugLog.d(TAG + "【Drop temp table】" + tempTableName);
            } catch (SQLException e) {
                DebugLog.d(TAG+ "【Failed to restore data from temp table 】" + tempTableName+e.toString());
            }
        }
    }

    /**
     * 得到列名
     * @param db 数据库
     * @param tableName 表名
     * @return  表
     */
    private static List<String> getColumns(Database db, String tableName) {
        List<String> columns = null;
        Cursor cursor = null;
        try {
            cursor = db.rawQuery("SELECT * FROM " + tableName + " limit 0", null);
            if (null != cursor && cursor.getColumnCount() > 0) {
                columns = Arrays.asList(cursor.getColumnNames());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null)
                cursor.close();
            if (null == columns)
                columns = new ArrayList<>();
        }
        return columns;
    }
}
